<template>
  <div class="spec-preview">
    <img :src="defaultImg.imgUrl" />
    <div
      class="event"
      @mouseenter="isShow = true"
      @mouseleave="isShow = false"
      @mousemove="getMouseLocation"
      ref="eventRef"
    ></div>
    <div class="big" v-show="isShow">
      <img ref="bigRef" :src="defaultImg.imgUrl" />
    </div>
    <div class="mask" ref="maskRef" v-show="isShow"></div>
  </div>
</template>

<script>
export default {
  name: "Zoom",
  props: ["skuInfoList"],
  data() {
    return {
      isShow: false,
      index:0
    };
  },
  computed: {
    defaultImg() {
      return this.skuInfoList[this.index] || {};
    },
  },
  mounted(){
    this.$bus.$on('changeImage',this.changeImage)
  },
  methods: {
    changeImage(index){
      this.index = index
    },
    getMouseLocation(e) {
      let startX = e.offsetX;
      let startY = e.offsetY;
      // console.log(startX, startY);
      let endX = startX - this.$refs.maskRef.offsetWidth / 2;
      let endY = startY - this.$refs.maskRef.offsetHeight / 2;

      if (endX < 0) {
        endX = 0;
        // 大盒子的宽 - 蒙层的宽 是鼠标水平移动的最大位置,当大于这个位置的时候,把鼠标的位置设置成最大值
      } else if (
        endX >
        this.$refs.eventRef.offsetWidth - this.$refs.maskRef.offsetWidth
      ) {
        endX = this.$refs.eventRef.offsetWidth - this.$refs.maskRef.offsetWidth;
      }

      if (endY < 0) {
        endY = 0;
        // 大盒子的高 - 蒙层的高 是鼠标垂直移动的最大位置,当大于这个位置的时候,把鼠标的位置设置成最大值
      } else if (
        endY >
        this.$refs.eventRef.offsetHeight - this.$refs.maskRef.offsetHeight
      ) {
        endY =
          this.$refs.eventRef.offsetHeight - this.$refs.maskRef.offsetHeight;
      }

      this.$refs.maskRef.style.left = endX + "px";
      this.$refs.maskRef.style.top = endY + "px";

      // 蒙层是 0 到 200px
      // 大图   0 到 -400px
      // 他们之间是 -2 倍的关系

      this.$refs.bigRef.style.left = -2 * endX + "px";
      this.$refs.bigRef.style.top = -2 * endY + "px";
    },
  },
};
</script>

<style lang="less">
.spec-preview {
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid #ccc;

  img {
    width: 100%;
    height: 100%;
  }

  .event {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 998;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: rgba(0, 255, 0, 0.3);
    position: absolute;
    left: 0;
    top: 0;
    // display: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -1px;
    left: 100%;
    border: 1px solid #aaa;
    overflow: hidden;
    z-index: 998;
    // display: none;
    background: white;

    img {
      width: 200%;
      max-width: 200%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  // .event:hover~.mask,
  // .event:hover~.big {
  //   display: block;
  // }
}
</style>
